package com.groupscore.user.service;

import com.groupscore.user.dao.UserDao;
import com.groupscore.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    BCryptPasswordEncoder encoder;
    /**
     * 查询全部用户
     * @return
     */
    public List<User> findAll(){
        return userDao.findAll();
    }

    /**
     * 根据id查询用户
     */
    public User findUserById(String id){
        return userDao.findById(id).get();
    }

    /**
     * 增加用户
     */
    public void add(User user){
        user.setId(idWorker.nextId()+"");

        //密码加密
        user.setPassword(encoder.encode(user.getPassword()));
        userDao.save(user);
    }

    /**
     * 修改用户
     */
    public void update(User user){
        userDao.save(user);
    }

    /**
     * 删除用户
     */
    public void deleteById(String id){
        userDao.deleteById(id);
    }

    /**
     * 根据用户名登录密码登录
     */
    public User findByNameAndPassword(String name, String password){
        User user = userDao.findByName(name);
        if(user != null && encoder.matches(password, user.getPassword())){
            return user;
        }else {
            return null;
        }
    }
}
